import { Map, View } from 'ol'
import { getTopLeft, getWidth } from 'ol/extent'
import TileLayer from 'ol/layer/Tile'
import { fromLonLat, get as getProjecttion } from 'ol/proj'
import { WMTS as WMTS } from 'ol/source'
import WMTSTileGrid from 'ol/tilegrid/WMTS'

const createWMTSMap = () => {
  /**
   * 判断地图 地图 或者 注记图
   * @param index 索引号
   */
  const JudegBaseAndNoteByType = (index) => {
    let mapType = [
      ['vec', 'cva'],
      ['ter', 'cta'],
      ['img', 'cia']
    ]
    return mapType[index]
  }
  /**
   * 地图初始化(天地图
   * @param {index} 天地图类型:矢量图(0) 影像图(1) 地形图(2)
   * @param {key} 地图服务秘钥
   * @param {*} centerPosition 中心点的经纬度
   * @notice 参数不为空
   */
  const tiandituInit = (index, key) => {
    let mapType = null
    if (mapType == null) {
      let layerArr = JudegBaseAndNoteByType(index)
      // 地图注记 与 底图配置
      let projection = getProjecttion('EPSG:3857')
      let projectionExtent = projection.getExtent()
      let size = getWidth(projectionExtent) / 256
      let resolutions = []
      let matrixIds = []
      for (let z = 0; z < 18; z++) {
        resolutions[z] = size / Math.pow(2, z)
        matrixIds[z] = z
      }
      // 地图底图
      let layer_Base = new TileLayer({
        opacity: 1,
        source: new WMTS({
          url: `http://t{0-7}.tianditu.gov.cn/${layerArr[0]}_w/wmts?tk=${key}`,
          layer: layerArr[0],
          matrixSet: 'w',
          format: 'tiles',
          style: 'default',
          attributions: '@天地图,🌏使用WMTS服务',
          tileGrid: new WMTSTileGrid({
            origin: getTopLeft(projectionExtent),
            resolutions,
            matrixIds
          }),
          wrapX: true
        }),
        visible: true
      })
      let layer_Note = new TileLayer({
        opacity: 1,
        source: new WMTS({
          url: `http://t{0-7}.tianditu.gov.cn/${layerArr[1]}_w/wmts?tk=${key}`,
          layer: layerArr[1],
          matrixSet: 'w',
          format: 'tiles',
          style: 'default',
          tileGrid: new WMTSTileGrid({
            origin: getTopLeft(projectionExtent),
            resolutions,
            matrixIds
          }),
          wrapX: true
        }),
        visible: true
      })
      return { layer_Base, layer_Note }
    }
  }
  /**
   * 创建地图
   */
  const creatMap = (index, key) => {
    const layers = tiandituInit(index, key)
    return new Map({
      target: 'map', //地图容器div层的ID
      layers: [layers.layer_Base, layers.layer_Note],
      // 地图视图设置View层
      view: new View({
        center: fromLonLat([113.2, 23.1]), //中心点
        zoom: 6
      })
    })
  }
  return { creatMap, tiandituInit }
}

export default createWMTSMap
